import { camelCase } from 'lodash';
import qs from 'qs';
const search = window.location.search;

const blackList = ['titleWebView', 'urlWebView', 'data']

export const getUrlParam = (): {
  param: Record<string, string | number>;
  camelCaseParam: Record<string, string | number>;
} => {
  const url_param = sessionStorage.getItem('url_param');
  const url_camelCaseParam = sessionStorage.getItem('url_camelCaseParam');
  const _param = url_param ? JSON.parse(url_param) : {};
  const _camelCaseParam = url_camelCaseParam ? JSON.parse(url_camelCaseParam) : {};
  if (search) {
    const _paramTemp = qs.parse(search.replace('?', ''));
    const paramTemp = Object.fromEntries(Object.entries(_paramTemp).filter(([key]) => !blackList.includes(key)))
    const param = { ..._param, ...paramTemp, channelCode: paramTemp.ch ?? _param.channelCode ?? '' };
    const camelCaseParam = {
      ..._camelCaseParam,
      ...Object.fromEntries(Object.entries(param).map(([key, value]) => [camelCase(key), value])),
    };
    return { param, camelCaseParam };
  }
  return {
    param: _param,
    camelCaseParam: _camelCaseParam,
  };
};

if (search) {
  const { camelCaseParam, param } = getUrlParam();
  sessionStorage.setItem('url_camelCaseParam', JSON.stringify(camelCaseParam));
  sessionStorage.setItem('url_param', JSON.stringify(param));
}
